<template>
  <div class="student-dashboard">
    <h1 class="page-title">我的学习进度</h1>
    
    <!-- 学生信息卡片 -->
    <el-card class="student-info-card">
      <div class="student-header">
        <div class="student-avatar">
          <el-avatar :size="80" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"></el-avatar>
        </div>
        <div class="student-details">
          <h2>{{ studentName }}</h2>
          <div class="student-id">学号：{{ studentId }}</div>
          <div class="student-class">班级：{{ className }}</div>
        </div>
      </div>
      <el-divider></el-divider>
      <div class="study-progress">
        <h3>学习进度</h3>
        <div class="progress-container">
          <div v-for="(subject, index) in subjects" :key="index" class="subject-progress">
            <div class="subject-name">{{ subject.name }}</div>
            <el-progress 
              :percentage="subject.progress" 
              :color="getProgressColor(subject.progress)"
              :stroke-width="16"
              :show-text="false">
            </el-progress>
            <div class="progress-text">{{ subject.progress }}%</div>
          </div>
        </div>
      </div>
    </el-card>
    
    <!-- 学习分析图表 -->
    <div class="chart-container">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>知识点掌握情况</span>
            <el-select v-model="selectedSubject" placeholder="选择学科" size="small">
              <el-option
                v-for="subject in subjects"
                :key="subject.id"
                :label="subject.name"
                :value="subject.id">
              </el-option>
            </el-select>
          </div>
        </template>
        <div id="knowledge-chart" style="height: 300px;"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>练习情况统计</span>
            <el-select v-model="timeRange" placeholder="时间范围" size="small">
              <el-option label="最近一周" value="week"></el-option>
              <el-option label="最近一月" value="month"></el-option>
              <el-option label="最近三月" value="quarter"></el-option>
            </el-select>
          </div>
        </template>
        <div id="practice-chart" style="height: 300px;"></div>
      </el-card>
    </div>
    
    <!-- 推荐练习 -->
    <el-card class="recommend-card">
      <template #header>
        <div class="card-header">
          <span>推荐练习</span>
          <el-button type="primary" size="small" @click="refreshRecommendations">刷新推荐</el-button>
        </div>
      </template>
      <div class="recommend-list">
        <div v-for="(item, index) in recommendItems" :key="index" class="recommend-item">
          <div class="recommend-content">
            <div class="recommend-title">{{ item.title }}</div>
            <div class="recommend-desc">{{ item.description }}</div>
            <div class="recommend-tags">
              <el-tag size="small" type="info">{{ item.subject }}</el-tag>
              <el-tag size="small" type="success">{{ item.difficulty }}</el-tag>
              <el-tag size="small" type="warning">{{ item.type }}</el-tag>
            </div>
          </div>
          <div class="recommend-action">
            <el-button type="primary" size="small" @click="startPractice(item)">开始练习</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

const studentName = ref('');
const studentId = ref('');
const className = ref('');
const selectedSubject = ref('');
const timeRange = ref('week');

// 学科数据
const subjects = ref([]);

// 模拟推荐练习数据
const recommendItems = ref([
  {
    id: 1,
    title: '数学函数应用练习',
    description: '根据你最近的学习情况，建议巩固函数应用相关知识点',
    subject: '数学',
    difficulty: '中等',
    type: '专项练习'
  },
  {
    id: 2,
    title: '英语阅读理解专练',
    description: '针对你在英语阅读理解中的弱点进行专项训练',
    subject: '英语',
    difficulty: '困难',
    type: '阅读理解'
  },
  {
    id: 3,
    title: '物理力学综合练习',
    description: '巩固牛顿运动定律和能量守恒相关知识点',
    subject: '物理',
    difficulty: '简单',
    type: '综合练习'
  },
]);

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 60) {
    return '#ff9900';
  } else if (percentage < 80) {
    return '#409eff';
  } else {
    return '#67c23a';
  }
};

// 刷新推荐
const refreshRecommendations = async () => {
  try {
    // 实际项目中应该调用API获取推荐
    // const response = await axios.get('/api/student/recommendations');
    // recommendItems.value = response.data;
    
    // 这里模拟刷新
    recommendItems.value = [
      {
        id: 4,
        title: '化学元素周期表练习',
        description: '加强对元素周期表规律的理解和记忆',
        subject: '化学',
        difficulty: '中等',
        type: '知识点巩固'
      },
      {
        id: 5,
        title: '语文文言文阅读',
        description: '提高古文阅读理解能力，掌握常见文言虚词用法',
        subject: '语文',
        difficulty: '困难',
        type: '阅读理解'
      },
      {
        id: 6,
        title: '数学概率统计练习',
        description: '针对你在概率统计章节的薄弱环节进行专项练习',
        subject: '数学',
        difficulty: '中等',
        type: '专项练习'
      },
    ];
  } catch (error) {
    console.error('获取推荐失败:', error);
  }
};

// 开始练习
const startPractice = (item) => {
  console.log('开始练习:', item);
  // 跳转到练习页面
  // router.push(`/student/practice?id=${item.id}`);
};

// 初始化知识点掌握图表
const initKnowledgeChart = () => {
  const chartDom = document.getElementById('knowledge-chart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  const option = {
    radar: {
      indicator: [
        { name: '基础概念', max: 100 },
        { name: '计算能力', max: 100 },
        { name: '应用能力', max: 100 },
        { name: '解题速度', max: 100 },
        { name: '理解深度', max: 100 },
        { name: '创新思维', max: 100 }
      ]
    },
    series: [
      {
        name: '知识点掌握情况',
        type: 'radar',
        data: [
          {
            value: [85, 90, 75, 80, 70, 65],
            name: '当前水平',
            areaStyle: {
              color: 'rgba(26, 115, 232, 0.3)'
            },
            lineStyle: {
              color: '#1a73e8'
            },
            itemStyle: {
              color: '#1a73e8'
            }
          },
          {
            value: [70, 75, 60, 65, 55, 50],
            name: '班级平均',
            areaStyle: {
              color: 'rgba(144, 238, 144, 0.3)'
            },
            lineStyle: {
              color: 'lightgreen'
            },
            itemStyle: {
              color: 'lightgreen'
            }
          }
        ]
      }
    ]
  };
  
  myChart.setOption(option);
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 初始化练习情况图表
const initPracticeChart = () => {
  const chartDom = document.getElementById('practice-chart');
  if (!chartDom) return;
  
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['做题数量', '正确率']
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: [
      {
        type: 'value',
        name: '题目数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '正确率(%)',
        position: 'right',
        min: 0,
        max: 100
      }
    ],
    series: [
      {
        name: '做题数量',
        type: 'bar',
        data: [20, 15, 25, 30, 22, 18, 15]
      },
      {
        name: '正确率',
        type: 'line',
        yAxisIndex: 1,
        data: [85, 80, 75, 82, 88, 90, 85],
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#ff9900'
        },
        itemStyle: {
          color: '#ff9900'
        }
      }
    ]
  };
  
  myChart.setOption(option);
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 获取学生信息和学习进度
const getStudentInfo = async () => {
  try {
    // 首先尝试从localStorage直接获取学号信息
    const localStudentId = localStorage.getItem('studentId');
    if (localStudentId) {
      studentId.value = localStudentId;
      console.log('从localStorage获取到学号:', localStudentId);
    }
    
    // 从API获取学生信息和学习进度
    const response = await axios.get('/api/student/learning-progress', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data) {
      // 设置学生基本信息
      studentName.value = response.data.studentName || '未知学生';
      // 只有在API返回的学号存在且本地没有学号时才更新
      if (response.data.studentId && !studentId.value) {
        studentId.value = response.data.studentId;
      }
      className.value = response.data.className || '';
      
      // 设置学科进度数据
      if (response.data.subjects && response.data.subjects.length > 0) {
        subjects.value = response.data.subjects;
      } else {
        console.warn('未获取到学科进度数据');
        subjects.value = [];
      }
    } else {
      // 如果API调用失败，尝试从localStorage获取基本信息
      studentName.value = localStorage.getItem('studentName') || '未知学生';
      // 此处不重复设置studentId，因为已经在函数开始时设置过
      className.value = '';
      subjects.value = [];
    }
  } catch (error) {
    console.error('获取学生信息和学习进度失败:', error);
    // 如果API调用失败，尝试从localStorage获取基本信息
    studentName.value = localStorage.getItem('studentName') || '未知学生';
    // 此处不重复设置studentId，因为已经在函数开始时设置过
    className.value = '';
    subjects.value = [];
  }
};

onMounted(async () => {
  await getStudentInfo();
  
  // 设置默认选中的学科
  if (subjects.value.length > 0) {
    selectedSubject.value = subjects.value[0].id;
  }
  
  // 初始化图表
  nextTick(() => {
    initKnowledgeChart();
    initPracticeChart();
  });
});
</script>

<style scoped>
.student-dashboard {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.student-info-card {
  margin-bottom: 20px;
}

.student-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.student-avatar {
  margin-right: 20px;
}

.student-details h2 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.student-id, .student-class {
  color: #606266;
  margin-bottom: 5px;
}

.study-progress h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
}

.progress-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.subject-progress {
  display: flex;
  flex-direction: column;
}

.subject-name {
  margin-bottom: 5px;
  font-weight: 500;
}

.progress-text {
  align-self: flex-end;
  margin-top: 5px;
  color: #606266;
  font-size: 14px;
}

.chart-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommend-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.recommend-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  flex-direction: column;
  background-color: #fafafa;
  transition: all 0.3s;
}

.recommend-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.recommend-content {
  flex: 1;
}

.recommend-title {
  font-weight: 600;
  margin-bottom: 10px;
  color: #303133;
}

.recommend-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
  min-height: 40px;
}

.recommend-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 15px;
}

.recommend-action {
  text-align: right;
}

@media (max-width: 768px) {
  .chart-container {
    grid-template-columns: 1fr;
  }
  
  .recommend-list {
    grid-template-columns: 1fr;
  }
}
</style> 